<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加分类按钮 -->
    <el-row>
      <el-col>
        <el-button type="primary" @click="showAddCateDialog"
          >添加分类</el-button
        >
      </el-col>
    </el-row>
    <!-- 表格 -->
    <tree-table
      :data="catelist"
      :columns="columns"
      :selection-type="false"
      border
      show-index
      index-text="#"
      :expand-type="false"
      :stripe="false"
      :show-row-hover="false"
      class="treetable"
      :is-fold="isFold"
    >
      <!-- 是否有效 -->
      <template slot="isOk" slot-scope="scope">
        <i
          class="el-icon-success"
          style="color: lightgreen"
          v-if="scope.row.cat_deleted === false"
        ></i>
        <i class="el-icon-error" style="color: red" v-else></i>
      </template>

      <!-- 排序 -->
      <template slot="order" slot-scope="scope">
        <el-tag type="primary" v-if="scope.row.cat_level === 0">一级</el-tag>
        <el-tag type="success" v-else-if="scope.row.cat_level === 1"
          >二级</el-tag
        >
        <el-tag type="warning" v-else>三级</el-tag>
      </template>
      <!-- 操作 -->
      <template slot="ope" slot-scope="scope">
        <el-button
          type="primary"
          icon="el-icon-edit"
          size="mini"
          @click="showEditCateDialog(scope.row)"
          >编辑</el-button
        >
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          @click="deleteCate(scope.row.cat_id)"
          >删除</el-button
        >
      </template>
    </tree-table>
    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[3, 5, 10, 15]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      background
    >
    </el-pagination>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            class="cascader"
            v-model="parentids"
            :options="parentCateList"
            expandTrigger="hover"
            :props="cascaderProps"
            @change="handleChange"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog title="修改分类" :visible.sync="editDialogVisible" width="50%">
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类数据
      catelist: [],
      // 请求参数
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5,
      },
      //总条数
      total: 0,
      //定义表格各列
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          type: 'template',
          template: 'order',
        },
        {
          label: '操作',
          type: 'template',
          template: 'ope',
        },
      ],

      //控制添加分类对话框的显示与隐藏
      addCateDialogVisible: false,

      //定义添加分类的表单数据
      addCateForm: {},
      //定义添加分类的表单验证规则对象
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },

      //父级分类数据
      parentCateList: [],

      //指定级联选择器的配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },

      //选中的父级分类的id数组
      parentids: [],

      //控制编辑对话框的显示与隐藏
      editDialogVisible: false,
      //编辑对话框的表单数据
      editCateForm: {},
      //编辑对话框的表单验证规则对象
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },

      //存储点击的分类id
      cateId: '',
      //存储当前层级
      catLevel: '',

      //默认折叠 是否折叠
      isFold: true,
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    //获取商品分类列表数据
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      console.log(res)
      this.catelist = res.data.result
      this.total = res.data.total
    },

    /**
     * 分页操作
     */
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newCurrent) {
      this.queryInfo.pagenum = newCurrent
      this.getCateList()
    },

    //点击按钮，显示添加分类对话框
    showAddCateDialog() {
      this.getParentCateList()
      this.addCateDialogVisible = true
    },

    //获取父级分类数据
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级分类数据失败!')
      }
      this.parentCateList = res.data
    },

    //当选择项发生变化时触发
    handleChange() {
      console.log(this.parentids)
      //进行判断 如果parentids数组中的length大于0，证明选中了父级分类
      //反之，就说明没有选中任何父级分类
      if (this.parentids.length > 0) {
        //就给父级分类的id赋值
        this.addCateForm.cat_pid = this.parentids[this.parentids.length - 1]
        //为当前分类的等级赋值
        this.addCateForm.cat_level = this.parentids.length
        return
      } else {
        //就给父级分类的id赋值
        this.addCateForm.cat_pid = 0
        //为当前分类的等级赋值
        this.addCateForm.cat_level = 0
      }
    },

    //添加分类
    addCate() {
      // console.log(this.addCateForm)
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post(
          'categories',
          this.addCateForm
        )
        if (res.meta.status !== 201) {
          return this.$message.error('添加分类失败！')
        }
        this.$message.success('添加分类成功！')
        this.getCateList()
        this.addCateDialogVisible = false
      })
    },

    //监听对话框的关闭事件，重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.parentids = []
      this.addCateForm.cat_level = 0
      this.addCateForm.cat_pid = 0
    },

    //点击编辑按钮展示编辑对话框
    async showEditCateDialog(cate) {
      //在展示编辑对话框前根据id获取该分类数据
      const { data: res } = await this.$http.get('categories/' + cate.cat_id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取该分类信息失败！')
      }

      //把点击的该id存储在data中
      this.cateId = cate.cat_id
      //把当前分类层级保存在data数据中
      this.catLevel = cate.cat_level

      this.editCateForm = res.data
      this.editDialogVisible = true
    },

    //修改分类数据
    editCate() {
      //先验证规则
      this.$refs.editCateFormRef.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.put(
          `categories/${this.cateId}`,
          { cat_name: this.editCateForm.cat_name }
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改分类数据失败！')
        }
        this.$message.success('修改分类数据成功！')
        if (this.catLevel == 0) {
          this.isFold = true
        } else {
          this.isFold = false
        }
        this.getCateList()

        this.editDialogVisible = false
      })
    },

    //删除分类信息
    async deleteCate(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该分类信息, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((error) => error)
      if (confirmResult !== 'confirm') {
        return this.$message.info('取消删除该分类信息')
      }
      //发起网络请求，删除分类信息
      const { data: res } = await this.$http.delete(`categories/${id}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除该分类信息失败！')
      }
      this.$message.success('删除该分类信息成功！')
      this.isFold = false
      this.getCateList()
    },
  },
}
</script>

<style lang="less" scoped>
.treetable {
  margin-top: 15px;
}
.cascader {
  width: 100%;
}
</style>